package com.ffyc.resale.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ffyc.resale.dao.GoodTypeDao;
import com.ffyc.resale.dao.GoodTypesDao;
import com.ffyc.resale.dao.GoodsDao;
import com.ffyc.resale.model.GoodType;
import com.ffyc.resale.model.GoodTypes;
import com.ffyc.resale.model.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class GoodTypeService {
    @Autowired
    GoodTypeDao goodTypeDao;
    @Autowired
    GoodTypesDao goodTypeDaos;
    @Autowired
    GoodsDao goodsDaos;
    public List<GoodType> getTab(){
        List<GoodType> list = goodTypeDao.selectList(null);
        List<GoodTypes> all = goodTypeDaos.selectList(null);
        for (int i = 0; i < all.size(); i++) {
            for (int j = 0; j < list.size(); j++) {
                if(all.get(i).getTypeid()==list.get(j).getId()){
                    if(list.get(j).getList()==null){
                        list.get(j).setList(new ArrayList<>());
                    }
                    list.get(j).getList().add(all.get(i));
                }
            }
        }
        return list;
    }

    public void add(GoodType type) {
        goodTypeDao.insert(type);
    }

    public void update(GoodType type) {
        goodTypeDao.updateById(type);
    }

    public boolean delete(Integer id) {
        QueryWrapper<GoodTypes> queryWrapper = new QueryWrapper<GoodTypes>().eq("typeid", id);
        List<GoodTypes> list = goodTypeDaos.selectList(queryWrapper);
        if (!list.isEmpty()){
            return false;
        }
        goodTypeDao.deleteById(id);
        return true;
    }

    public Page<GoodTypes> getSubtype(GoodTypes goodTypes) {
        Page<GoodTypes> page = new Page<>(goodTypes.getPageNo(), goodTypes.getPageSize());
        QueryWrapper<GoodTypes> queryWrapper = new QueryWrapper<GoodTypes>().eq(goodTypes.getTypeid()!=null,"typeid",goodTypes.getTypeid());
        Page<GoodTypes> list = goodTypeDaos.selectPage(page, queryWrapper);
        List<GoodTypes> typesList = list.getRecords();
        for (GoodTypes types:typesList) {
            types.setTypeName(goodTypeDao.selectById(types.getTypeid()).getName());
        }
        return list;
    }

    public boolean deleteSubtype(Integer id) {
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<Goods>().eq("typesid", id);

        if (!goodsDaos.selectList(queryWrapper).isEmpty()){
            return false;
        }
        goodTypeDaos.deleteById(id);
        return true;
    }

    public void updateSubtype(GoodTypes goodTypes) {
        goodTypeDaos.updateById(goodTypes);
    }

    public void addSubtype(GoodTypes goodTypes) {
        goodTypeDaos.insert(goodTypes);
    }
}
